package com.vilynn.learning.sort;

import com.alibaba.fastjson.JSON;

/**
 * Created by weilin.wang on 2018/3/2
 */
public class Sort {

    public static void main(String[] args) {
        int length = 11;
        int[] a = new int[length];
        for (int i = 0; i < length; i++) {
            a[i] = i*10-(int)(Math.random()*100);
        }

        System.out.println(JSON.toJSONString(a));
        insertSort(a);
        System.out.println(JSON.toJSONString(a));
    }

    public static void bubbleSort(int[] a){
        for (int i = 1; i < a.length; i++) {
            for (int j = 0; j < a.length-i; j++) {
                if(a[j] > a[j+1]){
                    int temp = a[j+1];
                    a[j+1] = a[j];
                    a[j] = temp;
                }
            }
        }
    }

    public static void selectSort(int[] a){
        for (int i = 1; i < a.length; i++) {
            int index = a.length-i;
            for (int j = a.length-i; j >= 0; j--) {
                if(a[j] > a[index]){
                    index = j;
                }
            }
            int temp = a[a.length-i];
            a[a.length - i] = a[index];
            a[index] = temp;
        }
    }

    public static void insertSort(int[] a){
        for (int i = 1; i < a.length; i++) {
            int temp = a[i];
            int j = i-1;
            for (; j >= 0 && a[j] > temp; j--) {
                a[j+1] = a[j];
            }
            a[j+1] = temp;
        }
    }

}
